package com.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class AddFlightServlet
 */
public class AddFlightServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final static String DATASOURCE_NAME = "jdbc/FlyGreenwichAirline";
	
	private DataSource datasource;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public AddFlightServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String day = request.getParameter("day");
		Integer dayint = Integer.parseInt(day);
		String month = request.getParameter("month");
		Integer monthint = Integer.parseInt(month);
		String year = request.getParameter("year");
		String adddeparture = request.getParameter("adddeparture");
		String adddestination = request.getParameter("adddestination");
		String price = request.getParameter("price");
		String time = request.getParameter("time");
		String dayinString = String.format("%02d", dayint);
		String monthinString = String.format("%02d", monthint);
		String gotFlight = "";
		
		Integer flightno = 0;
		
		Timestamp timestamp = null;
		java.sql.Connection con=null;
		
		System.out.println("adddeparture: "+adddeparture);
		System.out.println("adddestination: "+adddestination);
		System.out.println("price: "+price);
		System.out.println("time: "+time);
		System.out.println("day: " +dayinString);
		System.out.println("month: "+monthinString);
		System.out.println("year: "+year);
		
		String date = monthinString + "/" + dayinString + "/" + year;
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		try {
			Date parsedDate = dateFormat.parse(date);
			timestamp = new Timestamp(parsedDate.getTime());
		} catch (ParseException e1) {
			e1.printStackTrace();
		}

    	String query = "SELECT flight_no FROM flight WHERE depart='"+ adddeparture +"' AND dest='"+ adddestination +"';";
    	String query2 = "INSERT INTO schedule (flight_id,datetime) values (?,?);";
    	
    	try{
    		
    		Context env = (Context) new InitialContext().lookup("java:comp/env");
			datasource = (DataSource) env.lookup(DATASOURCE_NAME);
    		
    		con = datasource.getConnection();
    		
    		java.sql.Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery (query);
            
            while(rs.next()){
            	flightno = rs.getInt(1);
            }
    	
            if(flightno != null && flightno != 0){
    		java.sql.PreparedStatement pst = con.prepareStatement(query2);
    	
    			pst.setInt(1, flightno);
    			pst.setTimestamp(2, timestamp);
    			pst.executeUpdate();
            }
    		
            rs.close();
            stmt.close();
            
    	}catch(SQLException e){
    		e.printStackTrace();
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if (con != null) con.close();
    		}catch(SQLException ignored){
    		ignored.printStackTrace();
    		}
    	}
    	
    	if(flightno == null || flightno == 0){
    		gotFlight = "no";
    	}else{
    		gotFlight = "yes";
    	}
    	
    	request.setAttribute("gotFlight", gotFlight);
    
    	String nextJSP = "/admin/index.jsp";
    	RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
    	dispatcher.forward(request,response);
	}

}
